package cn.tb.user.service.impl;

import cn.tb.basic.constants.BaseConstants;
import cn.tb.basic.dto.RegisterDto;
import cn.tb.basic.exception.BusinessException;
import cn.tb.basic.util.MD5Utils;
import cn.tb.basic.util.StrUtils;
import cn.tb.user.domain.Logininfo;
import cn.tb.user.domain.User;
import cn.tb.user.mapper.LogininfoMapper;
import cn.tb.user.mapper.UserMapper;
import cn.tb.user.service.IUserService;
import cn.tb.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tangbo
 * @since 2022-06-16
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;
    /**
     * 手机注册
     * @param dto
     */
    @Override
    public void registerByPhone(RegisterDto dto) {
        //1.空校验
        String phone = dto.getPhone();
        String smsCode = dto.getSmsCode();
        String password = dto.getPassword();
        String passwordRepeat = dto.getPasswordRepeat();
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(smsCode) ||StringUtils.isEmpty(password)||StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("参数异常");
        }
        //2.校验两次密码是否一致
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致！");
        }
        //3.判断短信验证码是否正确
        //3.1根据key获取Redis中存的验证码
        String smsCodeKey = BaseConstants.RegisterConstants.REGISTER_SMS_PREFIX+phone;
        Object smsTmp = redisTemplate.opsForValue().get(smsCodeKey);
        System.out.println(smsTmp.toString().split(":")[0]);
        //3.2拿不到，验证码过期
        if(smsTmp==null){
            throw new BusinessException("验证码已过期！！！");
        }
        //3.3拿到了，判断是否一致
        if(!smsCode.equalsIgnoreCase(smsTmp.toString().split(":")[0])){
            throw new BusinessException("验证码填写错误！！！");
        }
        //4.保存数据，但是要级联保存logininfo表
        //dto转为user
        User user = dto2User(dto);
        //user转为logininfo
        Logininfo logininfo = user2logininfo(user);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }



    private Logininfo user2logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        //一定要手动设置type 1是用户 0是员工
        logininfo.setType(1);
        return logininfo;
    }

    private User dto2User(RegisterDto dto) {
        User user = new User();
        user.setPhone(dto.getPhone());
        user.setUsername(dto.getPhone());
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        //盐值加密后的密码
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    /**
     * 邮箱注册完整
     * @param dto
     */
    @Override
    public void registerByEmail(RegisterDto dto) {
        //空校验
        String email = dto.getEmail();
        String emailCode = dto.getEmailCode();
        String emailPassword = dto.getEmailPassword();
        String emailPasswordRepeat = dto.getEmailPasswordRepeat();
        if(StringUtils.isEmpty(email)||StringUtils.isEmpty(emailCode) ||StringUtils.isEmpty(emailPassword)||StringUtils.isEmpty(emailPasswordRepeat)){
            throw new BusinessException("参数异常");
        }
        //校验两次密码是否一致
        if(!emailPassword.equals(emailPasswordRepeat)){
            throw new BusinessException("两次密码不一致！");
        }
        //判断两次验证码是否正确
        //1.根据key从Redis中获取验证码
        String emailCodeKey = BaseConstants.RegisterConstants.REGISTER_SMS_PREFIX+email;
        Object codeTmp = redisTemplate.opsForValue().get(emailCodeKey);
        //1.1拿不到，验证码过期
        if(codeTmp==null){
            throw new BusinessException("验证码已过期！！！");
        }
        //1.2拿到了，判断是否一致
        if(!emailCode.equalsIgnoreCase(codeTmp.toString().split(":")[0])){
            throw new BusinessException("验证码填写错误！！！");
        }
        //4.保存数据，但是要级联保存logininfo表
        //dto转为user
        User user = dto2User1(dto);
        //user转为logininfo
        Logininfo logininfo = user2logininfo1(user);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }
    private Logininfo user2logininfo1(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        //一定要手动设置type 1是用户 0是员工
        logininfo.setType(1);
        return logininfo;
    }

    private User dto2User1(RegisterDto dto) {
        User user = new User();
        user.setEmail(dto.getEmail());
        user.setUsername(dto.getEmail());
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        //盐值加密后的密码
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }



    //user的增删改都需要级联操作logininfo
    @Override
    public void update(User user) {
        Logininfo logininfo1 = user2logininfoUpt(user);
        logininfoMapper.update(logininfo1);
        super.update(user);
    }

    private Logininfo user2logininfoUpt(User user) {
        Logininfo logininfo = new Logininfo();
        User userTmp = userMapper.loadById(user.getId());
        String pwdTmp = MD5Utils.encrypByMd5(user.getPassword() + userTmp.getSalt());
        if( ! pwdTmp.equals(userTmp.getPassword())){
            user.setPassword(pwdTmp);
            BeanUtils.copyProperties(user,logininfo);
        }
        return logininfo;
    }


    @Override
    public void deleteById(Long id) {
        super.deleteById(id);
    }
}
